package com.lk.common.utils;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

/**
 * 重定向工具类
 * @author lijun
 * @version 2018-05-03
 */
public class RedirectUtils {
	
	/**
	 * 重定向函数
	 * @param url 重定向地址
	 */
	public static String redirectTo(String url) {
		StringBuffer rto = new StringBuffer("redirect:");
		rto.append(url);
		return rto.toString();
	}
	
	/**
	 * 重定向函数
	 * @param url 重定向地址
	 * @param rtParams 重定向参数
	 */
	public static String redirectTo(String url,Map<String,String> rtParams) {
		StringBuffer rto = new StringBuffer("redirect:");
		rto.append(url);
		if(rtParams.size()>0) {
			rto.append("?");
			Iterator<String> it = rtParams.keySet().iterator();
			while(it.hasNext()) {
				String key = it.next();
				String value = rtParams.get(key);
				rto.append(key + "=" + value + "&");
			}
			rto.deleteCharAt(rto.length()-1);
		}
		return rto.toString();
	}
	
	/**
	 * 重定向函数
	 * @param response
	 * @param url 重定向地址
	 * @throws IOException 
	 */
	public static void redirectTo(HttpServletResponse response,String url) throws IOException {
		response.sendRedirect(url);
	}
	
	/**
	 * 重定向函数
	 * @param response
	 * @param url 重定向地址
	 * @param rtParams 重定向参数
	 * @throws IOException 
	 */
	public static void redirectTo(HttpServletResponse response,String url,Map<String,String> rtParams) throws IOException {
		if(rtParams.size()>0){
			StringBuffer ps = new StringBuffer("?");
			Iterator<String> it = rtParams.keySet().iterator();
			while(it.hasNext()) {
				String key = it.next();
				String value = rtParams.get(key);
				ps.append(key + "=" + value + "&");
			}
			ps.deleteCharAt(ps.length()-1);
			response.sendRedirect(url+ps);
		}else{
			response.sendRedirect(url);
		}			
	}
}
